<template>
  <div class="weight-list-container">
    <PageHeader content="体重历史记录管理"></PageHeader>
    
    <!-- 查询表单 -->
    <Card shadow="hover" class="mt-4">
      <Form :model="searchForm" inline>
        <FormItem label="记录日期范围">
          <DatePicker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          ></DatePicker>
        </FormItem>
        <FormItem label="体重区间">
          <Input v-model="searchForm.minWeight" placeholder="最小体重" type="number" style="width: 100px;"></Input>
          <span style="margin: 0 8px;">-</span>
          <Input v-model="searchForm.maxWeight" placeholder="最大体重" type="number" style="width: 100px;"></Input>
        </FormItem>
        <FormItem>
          <Button type="primary" @click="getWeightList">查询</Button>
          <Button @click="resetSearch">重置</Button>
        </FormItem>
      </Form>
    </Card>

    <!-- 新增按钮 -->
    <Button type="success" @click="openAddDialog" class="mt-4">新增体重记录</Button>

    <!-- 体重记录表格 -->
    <Table :data="tableData" border stripe :loading="loading" class="mt-4" style="width: 100%;">
      <TableColumn label="ID" prop="id" width="80"></TableColumn>
      <TableColumn label="体重(kg)" prop="weight" width="120"></TableColumn>
      <TableColumn label="记录日期" prop="recordDate" width="150"></TableColumn>
      <TableColumn label="备注" prop="note"></TableColumn>
      <TableColumn label="操作" width="200" fixed="right">
        <template slot-scope="scope">
          <Button size="small" type="primary" @click="openViewDialog(scope.row)">查看</Button>
          <Button size="small" type="warning" @click="openEditDialog(scope.row)">编辑</Button>
          <Button size="small" type="error" @click="handleDelete(scope.row)">删除</Button>
        </template>
      </TableColumn>
    </Table>

    <!-- 分页 -->
    <Page
      @on-size-change="handleSizeChange"
      @on-change="handleCurrentChange"
      :current="pageNum"
      :page-size="pageSize"
      :total="total"
      show-sizer
      show-total
      show-elevator
      class="mt-4"
      style="text-align: right;"
    ></Page>

    <!-- 新增/编辑弹窗 -->
    <Modal :title="dialogTitle" v-model="dialogVisible" width="500">
      <Form :model="formData" :rules="formRules" ref="formRef" label-width="100px">
        <FormItem label="体重(kg)" prop="weight">
          <Input v-model="formData.weight" type="number" step="0.1" placeholder="请输入体重"></Input>
        </FormItem>
        <FormItem label="记录日期" prop="recordDate">
          <DatePicker v-model="formData.recordDate" type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd" placeholder="请选择日期"></DatePicker>
        </FormItem>
        <FormItem label="备注" prop="note">
          <Input v-model="formData.note" type="textarea" :rows="3" placeholder="可选备注"></Input>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="dialogVisible = false">取消</Button>
        <Button type="primary" @click="submitForm">确定</Button>
      </div>
    </Modal>

    <!-- 查看弹窗 -->
    <Modal title="记录详情" v-model="viewVisible" width="500">
      <Descriptions :column="1" border>
        <DescriptionsItem label="ID">{{ viewData.id || '-' }}</DescriptionsItem>
        <DescriptionsItem label="体重(kg)">{{ viewData.weight || '-' }}</DescriptionsItem>
        <DescriptionsItem label="记录日期">{{ viewData.recordDate || '-' }}</DescriptionsItem>
        <DescriptionsItem label="备注">{{ viewData.note || '无' }}</DescriptionsItem>
        <DescriptionsItem label="创建人">{{ viewData.createBy || '-' }}</DescriptionsItem>
      </Descriptions>
    </Modal>
  </div>
</template>

<script>
import request from '@/utils/request';
import dayjs from 'dayjs';

export default {
  name: 'weightRecordList', // 与路由name一致，支持缓存
  data() {
    return {
      tableData: [],
      loading: false,
      total: 0,
      pageNum: 1,
      pageSize: 10,
      searchForm: { dateRange: [], minWeight: '', maxWeight: '' },
      dialogVisible: false,
      dialogTitle: '新增体重记录',
      formData: { id: '', weight: '', recordDate: dayjs().format('YYYY-MM-DD'), note: '' },
      formRules: {
        weight: [{ required: true, message: '请输入体重', trigger: 'blur' }, { type: 'number', min: 0.1, message: '体重需大于0', trigger: 'blur' }],
        recordDate: [{ required: true, message: '请选择记录日期', trigger: 'blur' }]
      },
      viewVisible: false,
      viewData: {}
    };
  },
  mounted() {
    this.getWeightList();
  },
  methods: {
    async getWeightList() {
      this.loading = true;
      try {
        const res = await request({
          url: '/weighthis/list',
          method: 'POST',
          data: {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            startDate: this.searchForm.dateRange[0] || '',
            endDate: this.searchForm.dateRange[1] || '',
            minWeight: this.searchForm.minWeight || '',
            maxWeight: this.searchForm.maxWeight || ''
          }
        });
        this.tableData = res.records;
        this.total = res.total;
      } catch (error) {
        console.error('查询体重记录失败', error);
      } finally {
        this.loading = false;
      }
    },
    resetSearch() {
      this.searchForm = { dateRange: [], minWeight: '', maxWeight: '' };
      this.getWeightList();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getWeightList();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.getWeightList();
    },
    openAddDialog() {
      this.dialogTitle = '新增体重记录';
      this.formData = { id: '', weight: '', recordDate: dayjs().format('YYYY-MM-DD'), note: '' };
      this.dialogVisible = true;
    },
    openEditDialog(row) {
      this.dialogTitle = '编辑体重记录';
      this.formData = { ...row };
      this.dialogVisible = true;
    },
    openViewDialog(row) {
      this.viewData = { ...row };
      this.viewVisible = true;
    },
    async submitForm() {
      this.$refs.formRef.validate(async (isValid) => {
        if (isValid) {
          try {
            if (this.formData.id) {
              await request({ url: '/weighthis/update', method: 'POST', data: this.formData });
            } else {
              await request({ url: '/weighthis/addnew', method: 'POST', data: this.formData });
            }
            this.dialogVisible = false;
            this.getWeightList();
          } catch (error) {
            console.error('提交失败', error);
          }
        }
      });
    },
    async handleDelete(row) {
      // 🔴 替换 Element MessageBox → iview Modal
      this.$Modal.confirm({
        title: '警告',
        content: '确定删除该记录？删除后不可恢复！',
        onOk: async () => {
          try {
            await request({ url: '/weighthis/delete', method: 'POST', data: { id: row.id } });
            this.getWeightList();
          } catch (error) {
            console.error('删除失败', error);
          }
        },
        onCancel: () => {
          this.$Notice.info({ title: '提示', desc: '已取消删除' });
        }
      });
    }
  }
};
</script>

<style scoped>
.weight-list-container {
  padding: 20px;
}
.mt-4 {
  margin-top: 16px;
}
</style>